package com.example.yskjproject.ui.activity;

import static com.tencent.cloud.tuikit.roomkit.model.ConferenceEventCenter.RoomKitUIEvent.BAR_SHOW_TIME_RECOUNT;
import static com.tencent.cloud.tuikit.roomkit.model.ConferenceEventCenter.RoomKitUIEvent.SHOW_OWNER_EXIT_ROOM_PANEL;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.opengl.Visibility;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListPopupWindow;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.android.tu.loadingdialog.LoadingDailog;
import com.example.yskjproject.R;
import com.example.yskjproject.base.BaseActivity;
import com.example.yskjproject.content.EventContent;
import com.example.yskjproject.databinding.ActivityClassRoomBinding;
import com.example.yskjproject.event.EventMessage;
import com.example.yskjproject.helper.SeriaPortHelper;
import com.example.yskjproject.helper.USBSerialHelper;
import com.example.yskjproject.http.Urls;
import com.example.yskjproject.http.callback.JsonCallback;
import com.example.yskjproject.model.ClassInfoModel;
import com.example.yskjproject.model.ClassStateModel;
import com.example.yskjproject.model.LzyResponse;
import com.example.yskjproject.model.RoomLiveInfoModel;
import com.example.yskjproject.utils.LogUtils;
import com.example.yskjproject.utils.SerialPortUtils;
import com.example.yskjproject.view.ToastFormat;
import com.example.yskjproject.view.dialog.PayDialog;
import com.example.yskjproject.view.dialog.WorkDialogHelper;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tencent.cloud.tuikit.engine.common.TUICommonDefine;
import com.tencent.cloud.tuikit.engine.room.TUIRoomDefine;
import com.tencent.cloud.tuikit.engine.room.TUIRoomEngine;
import com.tencent.cloud.tuikit.roomkit.ConferenceError;
import com.tencent.cloud.tuikit.roomkit.ConferenceMainFragment;
import com.tencent.cloud.tuikit.roomkit.ConferenceObserver;
import com.tencent.cloud.tuikit.roomkit.ConferenceParams;
import com.tencent.cloud.tuikit.roomkit.common.utils.RoomToast;
import com.tencent.cloud.tuikit.roomkit.model.ConferenceEventCenter;
import com.tencent.cloud.tuikit.roomkit.model.ConferenceState;
import com.tencent.cloud.tuikit.roomkit.model.entity.UserEntity;
import com.tencent.cloud.tuikit.roomkit.model.manager.ConferenceController;
import com.tencent.cloud.tuikit.roomkit.view.component.BaseDialogFragment;
import com.tencent.cloud.tuikit.roomkit.view.page.widget.FloatChat.view.IFloatChatDisplayView;
import com.tencent.cloud.tuikit.roomkit.view.page.widget.UserControlPanel.UserManagementPanel;
import com.tencent.cloud.tuikit.roomkit.viewmodel.UserManagementViewModel;
import com.tencent.cos.xml.utils.StringUtils;
import com.tencent.qcloud.tuicore.util.ToastUtil;
import com.xzh.imagepicker.ImagePicker;
import com.xzh.imagepicker.bean.MediaFile;
import com.yujing.utils.YConvert;
import com.yujing.yserialport.DataListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * ClassroomWorksActivity   我的工作室创建
 * <p>
 * 作者：zx
 * 创建时间：2024/5/3
 */
public class ClassroomWorksActivity extends BaseActivity<ActivityClassRoomBinding> implements USBSerialHelper.OnDataReceivedListener {
    ActivityClassRoomBinding classroomWorkBinding;
    private ConferenceObserver mConferenceObserver;
    boolean isCreate;
    Intent intent;
    String roomName = "", roomId = "", userName = "", userAvatar = "", userId = "";
    int studioWorkId;

    int courseId;//课程id

    int classTypeInt = 1;

    private List<String> listType = Lists.newArrayList("私教", "团课", "陪练", " 直播1");
    private ListPopupWindow listPopupWindowType;

    private List<String> listNum = Lists.newArrayList("1", "2", "3", " 4", "5", "6", "7");
    private ListPopupWindow listPopupWindowNum;

    private List<String> listTime = Lists.newArrayList("1", "5", "10", "15", "20", "30", "45", "60", "90");

    private ListPopupWindow listPopupWindowTime;


    private Gson gson = new Gson();

    private String studioId;

    private boolean isSelected = true;
    private boolean isCameraSelected = true;


    private boolean isDis = false;

    PayDialog payDialog;

    private long seconds = 0;

    private String TAG = "ClassroomWorksActivity";

    private int payState = 0; //0未支付 1已支付
    private int classState = 0; //0未开始 1空缺中 2已售完 3上课中 4 下课
    private String price;


    @Override
    protected ActivityClassRoomBinding getViewBinding() {
        classroomWorkBinding = ActivityClassRoomBinding.inflate(LayoutInflater.from(this));
        return classroomWorkBinding;
    }

    @Override
    protected boolean shouldShowTitle() {
        return false;
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageEvent(EventMessage eventMsg) {
        switch (eventMsg.getMessage()) {
            case EventContent.class_works_date://刷新支付信息
                ToastUtil.toastShortMessage("收到了下一状态变更得友盟通知");
                if (studioWorkId != -1) {
                    checkLive(studioWorkId);
                    Log.d(TAG, "收到支付刷新信息" + "studioWOrkId" + studioWorkId);
                }
//                if (studioWorkId != -1) {
//                    crateLive(studioWorkId);
//                }
                break;
            case EventContent.pay_ok://支付成功
                payDialog.dismiss();
                Log.d(TAG, "支付成功" + "studioWOrkId" + studioWorkId);
                classroomWorkBinding.downCurriculum.setText("已支付");
                classroomWorkBinding.downCurriculum.setBackground(getResources().getDrawable(R.drawable.btn_ty));
                if (studioWorkId != -1) {
                    checkLive(studioWorkId);
                }
                break;
        }
    }

    @Override
    protected void initData() {
        intent = getIntent();
        isCreate = intent.getBooleanExtra("isCreate", false);
        roomName = intent.getStringExtra("roomName");
        roomId = intent.getStringExtra("id");
        studioWorkId = intent.getIntExtra("studioWork", -1);
        courseId = intent.getIntExtra("courseId", -1);
        userId = intent.getStringExtra("userId");
        userName = intent.getStringExtra("userName");
        userAvatar = intent.getStringExtra("avatar_url");
        studioId = intent.getStringExtra("studio_id");
        price = intent.getStringExtra("price");
        mConferenceState = ConferenceController.sharedInstance().getConferenceState();
        getLiveRoomData();
        getOnClickInfo();
        Log.d(TAG,  "courseId " +courseId);

    }

    @Override
    protected void onResume() {
        super.onResume();
        //获取房间人数
//        memberCount = mRoomStore.getTotalUserCount();
//        String name = getString(com.tencent.cloud.tuikit.roomkit.R.string.tuiroomkit_item_member, memberCount);
    }

    /**
     * 创建多人视频
     */
    @SuppressLint("UseCompatLoadingForDrawables")
    private void getLiveRoomData() {
        ConferenceParams params = parseArguments();
        ConferenceMainFragment fragment = new ConferenceMainFragment();
        fragment.setConferenceParams(params);
        setConferenceObserver(fragment);
        if (isCreate) {
            classroomWorkBinding.upCurriculum.setVisibility(View.VISIBLE);
            classroomWorkBinding.upCurriculumPrompt.setVisibility(View.VISIBLE);
            classroomWorkBinding.downCurriculum.setText("开始上课");
            classroomWorkBinding.downCurriculum.setBackground(getResources().getDrawable(R.drawable.btn_ty));
//            classroomWorkBinding.downCurriculum.setBackground();
            classroomWorkBinding.downCurriculumDis.setText("（计时到课程时长后方可下课）");
            fragment.quickStartConference(roomId);
            if (studioWorkId != -1) {
                crateLive(studioWorkId);
            }
            classroomWorkBinding.workTv.setText("工作室设置");
        } else {
            fragment.joinConference(roomId);
            classroomWorkBinding.upCurriculum.setVisibility(View.GONE);
            classroomWorkBinding.upCurriculumPrompt.setVisibility(View.GONE);
            classroomWorkBinding.downCurriculum.setText("支付上课");
            classroomWorkBinding.downCurriculumDis.setText("（支付后不可取消）");
            if (studioWorkId != -1) {
                crateLive(studioWorkId);
            }
            classroomWorkBinding.workTv.setText("查看当前工作室");
        }
    }

    private void showEditWorkSpaceInfo(int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = getLayoutInflater().inflate(R.layout.workbase_edit, null);
        builder.setView(dialogView);
        final AlertDialog dialogProgress = builder.create();
        dialogProgress.setCancelable(false);
        EditText et_workstation_info = dialogView.findViewById(R.id.et_workstation_info);
        if (type == 1) {
            et_workstation_info.setMaxEms(30);
            et_workstation_info.setHint("请输入工作室名称");
        } else {
            et_workstation_info.setMaxEms(100);
            et_workstation_info.setHint("请输入工作室简介");
        }
        Button btn_format = dialogView.findViewById(R.id.btn_format);
        btn_format.setOnClickListener(view -> {
            if (TextUtils.isEmpty(et_workstation_info.getText())) {
                if (type == 1) {
                    ToastUtil.toastShortMessage("工作室名称不能为空");
                } else {
                    ToastUtil.toastShortMessage("工作室简介不能为空");
                }
            } else {
                if (type == 1) {
                    classroomWorkBinding.className.setText(et_workstation_info.getText().toString());
                } else {
                    classroomWorkBinding.classJs.setText(et_workstation_info.getText().toString());
                }
            }
            dialogProgress.dismiss();
        });

        dialogProgress.show();
    }

    private void getOnClickInfo() {
        if (TextUtils.isEmpty(price)) {
            classroomWorkBinding.classPrice.setText("1");
        } else {
            classroomWorkBinding.classPrice.setText(price + "");
        }
        classroomWorkBinding.ivAllView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (classroomWorkBinding.right.getVisibility() == View.VISIBLE) {
                    classroomWorkBinding.right.setVisibility(View.GONE);
                    classroomWorkBinding.left.setVisibility(View.GONE);
                    classroomWorkBinding.ivAllView.setBackgroundResource(R.drawable.exit_all_view);
                } else {
                    classroomWorkBinding.right.setVisibility(View.VISIBLE);
                    classroomWorkBinding.left.setVisibility(View.VISIBLE);
                    classroomWorkBinding.ivAllView.setBackgroundResource(R.drawable.all_view);
                }
            }
        });
        if (isCreate) {
            classroomWorkBinding.gzsNameUpdate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showEditWorkSpaceInfo(1);
                }
            });
            classroomWorkBinding.ivClassIntroduce.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showEditWorkSpaceInfo(2);
                }
            });
            if (payState > 0) {
                classroomWorkBinding.classJs.setInputType(InputType.TYPE_NULL);
                classroomWorkBinding.classPrice.setInputType(InputType.TYPE_NULL);
            }
            //全体静音
            classroomWorkBinding.btnMuteAll.setOnClickListener(allMute -> {
                if (isCreate) {
                    showDisableAllMicDialog();
                }

            });
            classroomWorkBinding.ivType.setOnClickListener(v -> {
                if (classState != 0) {
                    return;
                }
                if (isCreate) {
                    listPopupWindowType.show();
                }
            });
        }
        if (isCreate) {
            classroomWorkBinding.classNum.setEnabled(true);
        } else {
            classroomWorkBinding.classNum.setEnabled(false);
        }
        ConferenceController.sharedInstance().getRoomEngine().fetchRoomInfo(new TUIRoomDefine.GetRoomInfoCallback() {
            @Override
            public void onSuccess(TUIRoomDefine.RoomInfo roomInfo) {
                Log.e(TAG, new Gson().toJson(roomInfo));
            }

            @Override
            public void onError(TUICommonDefine.Error error, String message) {

            }
        });


        classroomWorkBinding.exitRoom.setOnClickListener(exitRoom -> {
            if (isCreate) {
                ConferenceController.sharedInstance().exitRoom(null);
            } else {
                ConferenceController.sharedInstance().exitRoom(null);
            }

            finish();
        });
        classroomWorkBinding.workSetting.setOnClickListener(setting -> {
            if (isCreate) {
                WorkDialogHelper workDialogHelper = new WorkDialogHelper(this, ClassroomWorksActivity.this, "setting");
                workDialogHelper.show();
            } else {
                WorkDialogHelper workDialogHelper = new WorkDialogHelper(this, ClassroomWorksActivity.this, "studioPeople");
                workDialogHelper.show();
            }


        });
        //摄像头
        classroomWorkBinding.imageCamera.setOnClickListener(camera -> {

            ConferenceEventCenter.getInstance().notifyUIEvent(BAR_SHOW_TIME_RECOUNT, null);
            if (isCameraSelected) {
                isCameraSelected = false;
                classroomWorkBinding.ivCamera.setImageResource(R.drawable.camera);
            } else {
                isCameraSelected = true;
                classroomWorkBinding.ivCamera.setImageResource(R.drawable.open_camera);
            }
            enableCamera(isCameraSelected);

        });
        //静音
        classroomWorkBinding.btnMute.setOnClickListener(mute -> {
            if (isSelected) {
                isSelected = false;
                classroomWorkBinding.ivMute.setImageResource(R.drawable.mute);
            } else {
                isSelected = true;
                classroomWorkBinding.ivMute.setImageResource(R.drawable.open_mute);
            }
            enableMicrophone(isSelected);
            ConferenceEventCenter.getInstance().notifyUIEvent(BAR_SHOW_TIME_RECOUNT, null);
        });

        classroomWorkBinding.llMember.setOnClickListener(member -> {
            //显示底部 成员列表
            ConferenceEventCenter.getInstance().notifyUIEvent(ConferenceEventCenter.RoomKitUIEvent.SHOW_USER_LIST, null);
            ConferenceEventCenter.getInstance().notifyUIEvent(BAR_SHOW_TIME_RECOUNT, null);
        });
        listPopupWindowType = new ListPopupWindow(this);
        ArrayAdapter<String> adapterConstellation = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listType);
        listPopupWindowType.setAdapter(adapterConstellation);
        listPopupWindowType.setAnchorView(classroomWorkBinding.tvType);//设置ListPopupWindow的锚点，关联mButton位置
        listPopupWindowType.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
        listPopupWindowType.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        listPopupWindowType.setModal(true);

        listPopupWindowType.setOnItemClickListener((parent, view, position, id) -> {
            classroomWorkBinding.tvType.setText(listType.get(position));
            listPopupWindowType.dismiss();
        });

        listPopupWindowNum = new ListPopupWindow(this);
        ArrayAdapter<String> adapterConstellation2 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listNum);
        listPopupWindowNum.setAdapter(adapterConstellation2);
        listPopupWindowNum.setAnchorView(classroomWorkBinding.classNum);//设置ListPopupWindow的锚点，关联mButton位置
        listPopupWindowNum.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
        listPopupWindowNum.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        listPopupWindowNum.setModal(true);
        classroomWorkBinding.ivClassNum.setOnClickListener(v -> {
            if (classState != 0) {
                return;
            }
            if (isCreate) {
                listPopupWindowNum.show();
            }
        });
        listPopupWindowNum.setOnItemClickListener((parent, view, position, id) -> {
            classroomWorkBinding.classNum.setText("1V" + listNum.get(position));
            listPopupWindowNum.dismiss();
        });


        listPopupWindowTime = new ListPopupWindow(this);
        ArrayAdapter<String> adapterConstellationTime = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listTime);
        listPopupWindowTime.setAdapter(adapterConstellationTime);
        listPopupWindowTime.setAnchorView(classroomWorkBinding.classTime);//设置ListPopupWindow的锚点，关联mButton位置
        listPopupWindowTime.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
        listPopupWindowTime.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        listPopupWindowTime.setModal(true);
        classroomWorkBinding.classTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (classState != 0) {
                    return;
                }
                if (isCreate) {
                    listPopupWindowTime.show();

                }
            }
        });
        listPopupWindowTime.setOnItemClickListener((parent, view, position, id) -> {
            classroomWorkBinding.classTime.setText(listTime.get(position));
            classroomWorkBinding.tvTimeCount.setText(classroomWorkBinding.classTime.getText().toString().trim() + ":00");
            listPopupWindowTime.dismiss();
        });

        //上线课程
        classroomWorkBinding.upCurriculum.setOnClickListener(upClass -> {
            if (classroomWorkBinding.upCurriculum.getText().toString().equals("上线课程")) {
                classTypeInt = 1;
                String className = classroomWorkBinding.className.getText().toString().trim();
                if (className.isEmpty()) {
                    ToastUtil.toastShortMessage("课程名称不能为空！");
                    return;
                }
                String classJs = classroomWorkBinding.classJs.getText().toString().trim();
                String classType = classroomWorkBinding.tvType.getText().toString().trim();
                if (classType.isEmpty()) {
                    ToastUtil.toastShortMessage("课程类型不能为空！");
                    return;
                }
                String classNum = classroomWorkBinding.classNum.getText().toString().trim();
                int index = classNum.indexOf("V");
                String result = classNum.substring(index + 1); // 截取逗号后面的内容
                String classTime = classroomWorkBinding.classTime.getText().toString().trim();
                String classPrice = classroomWorkBinding.classPrice.getText().toString().trim();
                int type = 0;
                switch (classType) {
                    case "私教":
                        type = 1;
                        break;
                    case "团课":
                        type = 2;
                        break;
                    case "陪练":
                        type = 3;
                        break;
                    case "直播":
                        type = 4;
                        break;
                }
                if (result.isEmpty()) {
                    ToastUtil.toastShortMessage("人数不能为空！");
                    return;
                }
                if (classTime.isEmpty()) {
                    ToastUtil.toastShortMessage("时长不能为空！");
                    return;
                }

                int Time = Integer.parseInt(classTime) * 60;
                if (classJs.isEmpty()) {
                    ToastUtil.toastShortMessage("课程介绍不能为空！");
                    return;
                }

                if (classPrice.isEmpty()) {
                    ToastUtil.toastShortMessage("课程价格不能为空！");
                    return;
                }
                //为什么要乘100
                // 创建一个AlertDialog.Builder
                AlertDialog.Builder builder = new AlertDialog.Builder(ClassroomWorksActivity.this);
                builder.setTitle("上线课程");
                builder.setMessage("确定要上线课程吗？");
                int finalType = type;
                builder.setPositiveButton("是", (dialog, which) -> {
                    // 在这里处理“是”按钮的点击事件
                    upClassPrompt(className, finalType, result, classJs, Time, Integer.parseInt(classPrice));
                });
                builder.setNegativeButton("否", (dialog, which) -> dialog.dismiss());
                AlertDialog dialog = builder.create();
                dialog.show();
            } else{
                if (classState == 1  && payState == 0) {
                    AlertDialog dialogKqz = getAlertDialog();
                    dialogKqz.show();
                }
            }

        });
        classroomWorkBinding.downCurriculum.setOnClickListener(startSK -> {
            if (payState > 0 && classroomWorkBinding.downCurriculum.getText().equals("开始上课")) {
                if (courseId != -1) {
                    curriculumState(courseId, 1);
                }
            } else if (classroomWorkBinding.downCurriculum.getText().equals("下课") && classState == 4 && isCreate) {
                xkAlertDialog().show();
            } else if (classroomWorkBinding.downCurriculum.getText().equals("支付上课")) {
                if (studioWorkId == -1) {
                    ToastUtil.toastShortMessage("找不到工作室id");
                    return;
                }
                payDialog = new PayDialog(this, String.valueOf(studioWorkId));
                payDialog.show();
            }
        });
    }


    private AlertDialog getAlertDialog() {
        AlertDialog.Builder builderKqz = new AlertDialog.Builder(ClassroomWorksActivity.this);
        builderKqz.setTitle("下线课程");
        builderKqz.setMessage("确定要执行这个操作吗？");
        builderKqz.setPositiveButton("是", (dialog, which) -> {
            // 在这里处理“是”按钮的点击事件
            if (courseId != -1) {
                curriculumState(courseId, 2);
            }
        });
        builderKqz.setNegativeButton("否", (dialogKqz, which) -> dialogKqz.dismiss());
        AlertDialog dialogKqz = builderKqz.create();
        return dialogKqz;
    }


    private AlertDialog xkAlertDialog() {
        AlertDialog.Builder builderKqz = new AlertDialog.Builder(ClassroomWorksActivity.this);
        builderKqz.setTitle("下课");
        builderKqz.setMessage("确定要下课吗？");
        builderKqz.setPositiveButton("是", (dialog, which) -> {
            LogUtils.d("xkAlertDialog down class courseId " + courseId);
            if (courseId != -1) {
                curriculumState(courseId, 1);
            }
        });
        builderKqz.setNegativeButton("否", (dialogKqz, which) -> dialogKqz.dismiss());
        AlertDialog dialogKqz = builderKqz.create();
        return dialogKqz;
    }

    private void enableCamera(boolean enable) {
        if (!enable) {
            ConferenceController.sharedInstance().closeLocalCamera();
            return;
        }
        if (!isOnSeatInSeatMode()) {
            RoomToast.toastShortMessageCenter(getString(com.tencent.cloud.tuikit.roomkit.R.string.tuiroomkit_please_raise_hand));
            return;
        }
        if (!isCameraAvailableInAllBanCameraMode()) {
            RoomToast.toastShortMessageCenter(getString(com.tencent.cloud.tuikit.roomkit.R.string.tuiroomkit_can_not_open_camera));
            return;
        }
        ConferenceController.sharedInstance().openLocalCamera(null);
    }

    private ConferenceState mConferenceState;

    private boolean isOnSeatInSeatMode() {
        return !mConferenceState.roomInfo.isSeatEnabled || mConferenceState.userModel.isOnSeat();
    }

    private boolean isCameraAvailableInAllBanCameraMode() {
        return !(mConferenceState.roomInfo.isCameraDisableForAllUser && mConferenceState.userModel.getRole() == TUIRoomDefine.Role.GENERAL_USER);
    }


    private void enableMicrophone(boolean enable) {
        if (enable) {
            ConferenceController.sharedInstance().enableLocalAudio();
        } else {
            ConferenceController.sharedInstance().disableLocalAudio();
        }
    }

    private void showDisableAllMicDialog() {
        boolean isDisable = ConferenceController.sharedInstance().getConferenceState().roomInfo.isMicrophoneDisableForAllUser;
        BaseDialogFragment.build().setTitle(getString(isDisable ? com.tencent.cloud.tuikit.roomkit.R.string.tuiroomkit_dialog_unmute_all_audio_title : com.tencent.cloud.tuikit.roomkit.R.string.tuiroomkit_dialog_mute_all_audio_title)).setContent(getString(isDisable ? com.tencent.cloud.tuikit.roomkit.R.string.tuiroomkit_dialog_unmute_all_audio_content : com.tencent.cloud.tuikit.roomkit.R.string.tuiroomkit_dialog_mute_all_audio_content)).setNegativeName(getString(com.tencent.cloud.tuikit.roomkit.R.string.tuiroomkit_cancel)).setPositiveName(getString(isDisable ? com.tencent.cloud.tuikit.roomkit.R.string.tuiroomkit_dialog_unmute_all_confirm : com.tencent.cloud.tuikit.roomkit.R.string.tuiroomkit_mute_all_audio)).setPositiveListener(new BaseDialogFragment.ClickListener() {
            @Override
            public void onClick() {
                if (isDisable && !ConferenceController.sharedInstance().getConferenceState().roomInfo.isMicrophoneDisableForAllUser) {
                    RoomToast.toastShortMessageCenter(getString(com.tencent.cloud.tuikit.roomkit.R.string.tuiroomkit_toast_not_mute_all_audio));
                    return;
                }
                if (!isDisable && ConferenceController.sharedInstance().getConferenceState().roomInfo.isMicrophoneDisableForAllUser) {
                    RoomToast.toastShortMessageCenter(getString(com.tencent.cloud.tuikit.roomkit.R.string.tuiroomkit_mute_all_mic_toast));
                    return;
                }
                if (!isDisable) {
                    classroomWorkBinding.ivAllMute.setImageResource(R.drawable.open_all_mute);
                } else {
                    classroomWorkBinding.ivAllMute.setImageResource(R.drawable.all_mute);
                }
                ConferenceController.sharedInstance().disableDeviceForAllUserByAdmin(TUIRoomDefine.MediaDevice.MICROPHONE, !isDisable, null);

            }
        }).showDialog(this, "disableDeviceForAllUserByAdmin");
    }

    private void upClassPrompt(String className, int classType, String classNum, String classJs, int classTime, int price) {
        Map<String, Object> jsonParams = new HashMap<>();
        jsonParams.put("tag_lv1_id", classType);
        jsonParams.put("max_quantity", classNum);
        jsonParams.put("course_name", className);
        jsonParams.put("description", classJs);
        jsonParams.put("duration", classTime);
        jsonParams.put("price", price * 100);
        String paramsDate = gson.toJson(jsonParams);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramsDate);
        OkGo.<LzyResponse<ClassInfoModel>>post(Urls.CREATE_CLASS).upRequestBody(requestBody).execute(new JsonCallback<LzyResponse<ClassInfoModel>>() {
            @SuppressLint("SimpleDateFormat")
            @Override
            public void onSuccess(Response<LzyResponse<ClassInfoModel>> response) {
                ClassInfoModel classInfoModel = response.body().data;
                if (classInfoModel != null) {
                    courseId = classInfoModel.getId();
                }
                isDis = false;
                payState = 0;
                classState = response.body().data.getState();
                displayState(classState, payState);
            }


            @Override
            public void onError(Response<LzyResponse<ClassInfoModel>> response) {
                super.onError(response);
                ToastUtil.toastShortMessage(response.getException().getMessage());
            }
        });
    }


    /**
     * 课程状态变更
     */
    private void curriculumState(int courseId, int stepState) {
        Map<String, Object> jsonParams = new HashMap<>();
        jsonParams.put("course_id", courseId);
        jsonParams.put("step_state", stepState);
        String paramsDate = gson.toJson(jsonParams);
        Log.e(TAG, "curriculumState=-==>" + paramsDate);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramsDate);
        OkGo.<LzyResponse<ClassStateModel>>post(Urls.CLASS_STATE).upRequestBody(requestBody).execute(new JsonCallback<LzyResponse<ClassStateModel>>() {
            @SuppressLint({"SimpleDateFormat", "UseCompatLoadingForDrawables"})
            @Override
            public void onSuccess(Response<LzyResponse<ClassStateModel>> response) {
                LogUtils.d("curriculumState=-==>success" + response.body().data.getStep_msg() + " course_state " + response.body().data.getCourse_info().getState());
                ClassStateModel classStateModel = response.body().data;
                if (classStateModel != null) {
                    if (!classStateModel.getStep_msg().equals("Success")) {
                        ToastUtil.toastShortMessage(classStateModel.getStep_msg());
                    }
                    if (stepState == 2) {
                        KickOutPeople();
                    }
                }
                if (response.body().data.getCourse_info().getPay_num() > 0) {
                    payState = response.body().data.getCourse_info().getPay_num();
                } else {
                    payState = 0;
                }
                classState = response.body().data.getCourse_info().getState();
                displayState(classState, payState);
            }

            @Override
            public void onError(Response<LzyResponse<ClassStateModel>> response) {
                super.onError(response);
                ToastUtil.toastShortMessage(response.getException().getMessage());

            }
        });
    }

    private void displayState(int state, int orderNum) {
        LogUtils.d("state=" + state + "orderNum=" + orderNum + "isCreate" + isCreate);
        switch (state) {
            case 0://未开课
                if (!isCreate) {
                    classroomWorkBinding.kcState.setText("未开课");
                } else {
                    classroomWorkBinding.exitRoom.setVisibility(View.VISIBLE);
                    classroomWorkBinding.upCurriculum.setText("上线课程");
                    classroomWorkBinding.upCurriculum.setBackground(getResources().getDrawable(R.drawable.btn_ty2));
                    classroomWorkBinding.kcState.setText("未开课");
                    classroomWorkBinding.downCurriculum.setText("开始上课");
                    classroomWorkBinding.downCurriculum.setBackground(getResources().getDrawable(R.drawable.btn_ty));
                    isDis = false;
                }

                break;
            case 1:// 空缺中
                if (!isCreate) {
                    classroomWorkBinding.kcState.setText("空缺中");
                } else {
                    if (isDis) {
                        classroomWorkBinding.upCurriculum.setText("下线课程");
                        classroomWorkBinding.upCurriculum.setBackground(getResources().getDrawable(R.drawable.btn_ty));
                        classroomWorkBinding.kcState.setText("空缺中");
                        classroomWorkBinding.downCurriculum.setText("开始上课");
                        classroomWorkBinding.downCurriculum.setBackground(getResources().getDrawable(R.drawable.btn_ty2));
                    } else {
                        classroomWorkBinding.upCurriculum.setText("下线课程");
                        classroomWorkBinding.upCurriculum.setBackground(getResources().getDrawable(R.drawable.btn_ty2));
                        classroomWorkBinding.kcState.setText("空缺中");
                        classroomWorkBinding.downCurriculum.setText("开始上课");
                        classroomWorkBinding.downCurriculum.setBackground(getResources().getDrawable(R.drawable.btn_ty));
                    }
                    //上课之后 不能操作课程
                    classroomWorkBinding.className.setEnabled(false);
                    classroomWorkBinding.gzsNameUpdate.setVisibility(View.GONE);
                    classroomWorkBinding.classJs.setEnabled(false);
                    classroomWorkBinding.ivClassIntroduce.setVisibility(View.GONE);
                    classroomWorkBinding.classPrice.setEnabled(false);

                    classroomWorkBinding.exitRoom.setVisibility(View.INVISIBLE);
                }
                break;
            case 2://已售完（已满员）
                if (!isCreate) {
                    classroomWorkBinding.kcState.setText("已满员");
                    LogUtils.d(" is not create已满员");
                } else {
                    LogUtils.d(" is create已满员");
                    classroomWorkBinding.upCurriculum.setText("下线课程");
                    classroomWorkBinding.upCurriculum.setBackground(getResources().getDrawable(R.drawable.btn_ty));
                    classroomWorkBinding.kcState.setText("已满员");
                    classroomWorkBinding.downCurriculum.setText("开始上课");
                    classroomWorkBinding.downCurriculum.setBackground(getResources().getDrawable(R.drawable.btn_ty2));
                    classroomWorkBinding.exitRoom.setVisibility(View.INVISIBLE);
                    //上课之后 不能操作课程
                    classroomWorkBinding.className.setEnabled(false);
                    classroomWorkBinding.gzsNameUpdate.setVisibility(View.GONE);
                    classroomWorkBinding.classJs.setEnabled(false);
                    classroomWorkBinding.ivClassIntroduce.setVisibility(View.GONE);
                    classroomWorkBinding.classPrice.setEnabled(false);
                }

                break;
            case 3://上课中
                if (!isCreate) {
                    classroomWorkBinding.kcState.setText("上课中");
                    classroomWorkBinding.downCurriculum.setText("上课");
                }
                if (seconds != 0) {
                    startTime(seconds);
                } else {
                    int Time = Integer.parseInt(classroomWorkBinding.classTime.getText().toString().trim()) * 60;
                    startTime(Time * 1000L);
                }
                classroomWorkBinding.upCurriculum.setText("下线课程");
                classroomWorkBinding.upCurriculum.setBackground(getResources().getDrawable(R.drawable.btn_ty));
                classroomWorkBinding.kcState.setText("上课中");
                classroomWorkBinding.downCurriculum.setText("下课");
                classroomWorkBinding.downCurriculum.setBackground(getResources().getDrawable(R.drawable.btn_ty));
                classroomWorkBinding.exitRoom.setVisibility(View.INVISIBLE);
                //上课之后 不能操作课程
                classroomWorkBinding.className.setEnabled(false);
                classroomWorkBinding.gzsNameUpdate.setVisibility(View.GONE);
                classroomWorkBinding.classJs.setEnabled(false);
                classroomWorkBinding.ivClassIntroduce.setVisibility(View.GONE);
                classroomWorkBinding.classPrice.setEnabled(false);
                //处理倒计时------------
                if (seconds != 0) {
                    startTime(seconds);
                } else {
                    int Time = Integer.parseInt(classroomWorkBinding.classTime.getText().toString().trim()) * 60;
                    startTime(Time * 1000L);
                }
                break;
            case 4://下课
                if (!isCreate) {
                    classroomWorkBinding.kcState.setText("未开课");
                } else {
                    classroomWorkBinding.className.setEnabled(true);
                    classroomWorkBinding.gzsNameUpdate.setVisibility(View.VISIBLE);
                    classroomWorkBinding.classJs.setEnabled(true);
                    classroomWorkBinding.ivClassIntroduce.setVisibility(View.VISIBLE);
                    classroomWorkBinding.classPrice.setEnabled(true);
                    classroomWorkBinding.upCurriculum.setText("上线课程");
                    classroomWorkBinding.upCurriculum.setBackground(getResources().getDrawable(R.drawable.btn_ty2));
                    classroomWorkBinding.kcState.setText("未开课");
                    classroomWorkBinding.downCurriculum.setText("开始上课");
                    classroomWorkBinding.downCurriculum.setBackground(getResources().getDrawable(R.drawable.btn_ty));
                    classroomWorkBinding.exitRoom.setVisibility(View.VISIBLE);
                    KickOutPeople();
                }
                break;
        }
    }

    /**
     * 踢出所有人
     */
    private void KickOutPeople() {
        List<UserEntity> list = ConferenceController.sharedInstance().getConferenceState().allUserList;
        String localUserId = ConferenceController.sharedInstance().getConferenceState().userModel.userId;
        int count = 0;
        for (UserEntity user : list) {
            if (TextUtils.equals(user.getUserId(), localUserId) || user.getVideoStreamType() == TUIRoomDefine.VideoStreamType.SCREEN_STREAM) {
                UserManagementPanel userManagementPanel = new UserManagementPanel(this,user);
                userManagementPanel.showKickDialog(user.getUserId(),user.getUserName());
                return;
            }
        }

    }


    private void startTime(long time) {
        new CountDownTimer(time, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");//初始化Formatter的转换格式。
                formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
                String hms = formatter.format(millisUntilFinished);
                classroomWorkBinding.tvTimeCount.setText(hms);
            }

            @Override
            public void onFinish() {
                // TODO Auto-generated method stub
                if (isCreate) {
                    classState = 4;
                    classroomWorkBinding.downCurriculum.setText("下课");
                    classroomWorkBinding.downCurriculum.setBackground(getResources().getDrawable(R.drawable.btn_ty2));
                    KickOutPeople();
                }
            }
        }.start();

    }


    private ConferenceParams parseArguments() {
        ConferenceParams params = new ConferenceParams();
        params.setName(roomName);
        params.setEnableSeatControl(false);
        params.setMuteMicrophone(intent.getBooleanExtra("muteMicrophone", false));
        params.setOpenCamera(intent.getBooleanExtra("openCamera", false));
        params.setSoundOnSpeaker(intent.getBooleanExtra("soundOnSpeaker", true));
        return params;
    }

    private void setConferenceObserver(ConferenceMainFragment fragment) {
        mConferenceObserver = new ConferenceObserver() {
            @Override
            public void onConferenceStarted(String conferenceId, ConferenceError error) {
                super.onConferenceStarted(conferenceId, error);
                showFragment(fragment, error);
            }

            @Override
            public void onConferenceJoined(String conferenceId, ConferenceError error) {
                super.onConferenceJoined(conferenceId, error);
                showFragment(fragment, error);
            }
        };
        fragment.setConferenceObserver(mConferenceObserver);
    }

    private void showFragment(Fragment fragment, ConferenceError error) {
        if (error != ConferenceError.SUCCESS) {
            ToastUtil.toastLongMessageCenter("Error : " + error);
            finish();
            return;
        }
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.add(R.id.conference_container, fragment);
        transaction.commitAllowingStateLoss();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == WorkDialogHelper.REQUEST_SELECT_IMAGES_CODE && resultCode == RESULT_OK) {
            List<MediaFile> mediaFiles = (List<MediaFile>) data.getSerializableExtra(ImagePicker.EXTRA_SELECT_IMAGES);
            final String Intent_Action = "com.android.BroadcastReceiver";//定义广播，方便我们接收这个广播
            Intent intent = new Intent(Intent_Action);
            intent.putExtra("mediaFiles", (Serializable) mediaFiles);
            sendBroadcast(intent);
//            EventBusUtil.sendEvent(new EventListMessage(EventContent.Pic_Video,mediaFiles));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mConferenceObserver = null;
    }


    private void crateLive(int studioId) {
        OkGo.<LzyResponse<RoomLiveInfoModel>>get(Urls.LIVE_INFO + "?studio_id=" + studioId).execute(new JsonCallback<LzyResponse<RoomLiveInfoModel>>() {
            @Override
            public void onSuccess(Response<LzyResponse<RoomLiveInfoModel>> response) {
                LogUtils.d("crateLive success orderList" + response.body().data.getOrder_list() + "  and isCreate " + isCreate);
                RoomLiveInfoModel data = response.body().data;
                if (data == null) {
                    return;
                }
                if (data.getStudio_info().getCourse_info() != null) {
                    courseId = data.getStudio_info().getCourse_info().getId();
                }
                if (data.getStudio_info() != null) {
                    if (data.getStudio_info().getCourse_info() != null) {
                        if (!StringUtils.isEmpty(data.getStudio_info().getCourse_info().getCourse_name())) {
                            if (!isCreate) {
                                classroomWorkBinding.classNameTv.setVisibility(View.VISIBLE);
                                classroomWorkBinding.className.setVisibility(View.GONE);
                                classroomWorkBinding.classNameTv.setText(data.getStudio_info().getCourse_info().getCourse_name());
                            } else {
                                classroomWorkBinding.className.setText(data.getStudio_info().getCourse_info().getCourse_name());
                            }

                        }
                        classroomWorkBinding.tvWorkspaceName.setText(data.getStudio_info().getTitle());
                        String type = "";
                        switch (data.getStudio_info().getCourse_info().getTag_lv1_id()) {
                            case 2:
                                type = "团课";
                                break;
                            case 3:
                                type = "陪练";
                                break;
                            case 4:
                                type = "直播";
                                break;
                            default:
                                type = "私教";
                                break;
                        }
                        classroomWorkBinding.tvType.setText(type);
                        classroomWorkBinding.classNum.setText(data.getStudio_info().getCourse_info().getMax_quantity() != 0 ? "1V" + data.getStudio_info().getCourse_info().getMax_quantity() : "0");
                        classroomWorkBinding.classTime.setText(data.getStudio_info().getCourse_info().getDuration() != 0 ? data.getStudio_info().getCourse_info().getDuration() / 60 + "" : "30");
                        classroomWorkBinding.tvTimeCount.setText(classroomWorkBinding.classTime.getText().toString().trim() + ":00");
                        classroomWorkBinding.classJs.setText(data.getStudio_info().getCourse_info().getDescription() != null ? data.getStudio_info().getCourse_info().getDescription() : "");
                        //增加倒计时
                        if (data.getStudio_info().getCourse_info().getEnd_time() > 0) {
                            ToastUtil.toastShortMessage("后台返回时间戳:" + data.getStudio_info().getCourse_info().getEnd_time());
                            //当前时间错
                            long nanoTimestamp = System.nanoTime();
                            ToastUtil.toastShortMessage("当前时间戳:" + nanoTimestamp);
                            //课程结束的时间戳
                            long endTime = data.getStudio_info().getCourse_info().getEnd_time();
                            //还有多少时间下课
                            long overTime = endTime - nanoTimestamp;
                            ToastUtil.toastShortMessage("还有多少秒下课:" + overTime);
                            // 将时间戳转换为秒
                            seconds = overTime / 1000;
                        }

                        if (data.getOrder_list() != null && !data.getOrder_list().isEmpty()) {
                            isDis = true;
                        }
                        ToastUtil.toastShortMessage("刚进房间得状态:" + data.getStudio_info().getCourse_info().getState());
                        classState = data.getStudio_info().getCourse_info().getState();
                        if (data.getOrder_list() != null) {
                            payState = data.getOrder_list().size();
                        } else {
                            payState = 0;
                        }
                        displayState(classState, payState);
                    }
                }
                if (data.getOrder_list() != null) {
                    payState = data.getOrder_list().size();
                    for (RoomLiveInfoModel.OrderListBean bean : data.getOrder_list()) {
                        if (!isCreate) {
                            if (bean.getLive_user_id().equals(userId)) {
                                if (bean.getState() == 2) {//支付后
                                    classroomWorkBinding.downCurriculum.setText("已支付");
                                    classroomWorkBinding.downCurriculum.setBackground(getResources().getDrawable(R.drawable.btn_ty));
                                }
                            }
                        }
                    }

                }
            }

            @Override
            public void onError(Response<LzyResponse<RoomLiveInfoModel>> response) {
                super.onError(response);
                ToastUtil.toastShortMessage(response.getException().getMessage());
            }
        });
    }


    private void checkLive(int studioId) {
        OkGo.<LzyResponse<RoomLiveInfoModel>>get(Urls.LIVE_INFO + "?studio_id=" + studioId).execute(new JsonCallback<LzyResponse<RoomLiveInfoModel>>() {
            @Override
            public void onSuccess(Response<LzyResponse<RoomLiveInfoModel>> response) {
                LogUtils.d("checkLive success" + " studioId " + studioId + " and " + response.body().data.getStudio_info().getCourse_info().getState());
                RoomLiveInfoModel data = response.body().data;
                if (data == null) {
                    return;
                }

                if (data.getOrder_list() != null && !data.getOrder_list().isEmpty()) {
                    isDis = true;
                }
                if (data.getOrder_list() != null) {
                    payState = data.getOrder_list().size();
                } else {
                    payState = 0;
                }
                classState = data.getStudio_info().getCourse_info().getState();
                displayState(classState, payState);
                Log.d(TAG, " getState :" + data.getStudio_info().getCourse_info().getState());
            }

            @Override
            public void onError(Response<LzyResponse<RoomLiveInfoModel>> response) {
                super.onError(response);
                ToastUtil.toastShortMessage(response.getException().getMessage());
            }
        });
    }


    @Override
    public void onDataReceived(byte[] data) {
        String receivedData = new String(data);
        ToastUtil.toastShortMessage("USBSerialHelper" + " Received data: " + receivedData);
        com.example.yskjproject.utils.Log.e("USBSerialHelper", "Received data: " + receivedData);
    }
}
